package com.winit.config.manager;

import com.alibaba.fastjson.JSONObject;
import com.winit.config.model.Config;
import com.winit.config.repository.ConfigOperations;
import com.winit.template.service.TemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by wangjian on 2017/9/28.
 */
@Component
public class ResourceConfigManager {

    private static Logger logger = LoggerFactory.getLogger(ResourceConfigManager.class);

    @Autowired
    ConfigOperations operations;
    @Autowired
    TemplateService templateService;

    public List<Config> getResourceList(UUID id, String appTag, String envTag, String zoneTag, String resourceTag) {
        //1、查询数据库中的记录
        List<Config> list = operations.getResourceConfig(id, appTag, envTag, zoneTag, resourceTag);
        //2、渲染引用key
        for (Config config : list) {
            getResourceAfterRander(config);
        }
        return list;
    }

    //获取radner后的resource对象
    public Config getResourceAfterRander(Config resource) {
        JSONObject k_v_preview_map = new JSONObject();
        /**
         * 1、从k v map 中获取key，判断是否用的渲染
         * 2、根据config_id获取渲染用的哪个config的k_v_map
         * 3、拼接数据 渲染模版
         */
        if(resource.getConfig_k_v_map() == null || resource.getConfig_k_v_ref_id() == null){
            return resource;
        }
        Set<String> keys = resource.getConfig_k_v_map().keySet();
        for (String key : keys) {
            String value = resource.getConfig_k_v_map().getString(key);
            if (!resource.getConfig_k_v_ref_id().containsKey(key)) {
                k_v_preview_map.put(key, value);
                continue;
            }

            List<Config> servers = new ArrayList<>();
            String[] ids = resource.getConfig_k_v_ref_id().getString(key).split(",");
            for (String i : ids) {
                servers.addAll(operations.getServerConfig(UUID.fromString(i), resource.getConfig_env_tag()
                        , resource.getConfig_zone_tag(), resource.getConfig_resource_tag()));
            }

            if (servers.size() == 0) {
                k_v_preview_map.put(key, value);
                continue;
            }

            //1.普通渲染
            if (!resource.getConfig_k_v_map().getString(key).contains("<#list ref_list")) {
                try {
                    value = templateService.render(resource.getConfig_k_v_map().getString(key), servers.get(0).getConfig_k_v_map());
                } catch (Exception e1) {
                    logger.error("com.winit.config.manager.ResourceConfigManager.getResourceAfterRander error",e1);
                }
            }else {
                //2.list 形式的渲染
                List dataList = new ArrayList();
                for (Config server : servers) {
                    dataList.add(server.getConfig_k_v_map());
                }
                Map dataModel = new HashMap();
                dataModel.put("ref_list", dataList);
                try {
                    value = templateService.render(resource.getConfig_k_v_map().getString(key), dataModel);
                } catch (Exception e) {
                    logger.error("com.winit.config.manager.ResourceConfigManager.getResourceAfterRander error",e);
                }
            }
            k_v_preview_map.put(key, value);
        }
        resource.setK_v_preview_map(k_v_preview_map);
        return resource;
    }

}
